package com.kexin.common.utils;


import org.springframework.util.StringUtils;

import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

public class UUCommonFun {

	public static String CreateMd5Sign(Map<String, Object> Parameters, String AppKey) {

		Map<String, Object> myParameters = SortMapByKey(Parameters);
		StringBuffer data = new StringBuffer();
		Iterator<String> iterator = myParameters.keySet().iterator();

		while (iterator.hasNext()) {
			String key = iterator.next();
			Object value = myParameters.get(key);
			if (key.toUpperCase() != "SIGN" && !StringUtils.isEmpty(value)) {
				data.append(String.format("%s=%s&", key, value));
			}
		}
		data.append("key=" + AppKey);

		String result = data.toString().toUpperCase();
		String sing = MD5Utils.string2MD5(result).toUpperCase();
		return sing;
	}

	private static Map<String, Object> SortMapByKey(Map<String, Object> oriMap) {
		if (oriMap == null || oriMap.isEmpty()) {
			throw new IllegalStateException("数组为空");
		}
		Map<String, Object> sortedMap = new TreeMap<String, Object>(new Comparator<String>() {
			@Override
			public int compare(String key1, String key2) {
				return key1.compareTo(key2);
			}
		});
		sortedMap.putAll(oriMap);
		return sortedMap;
	}

	public static String getTimeStamp() {
		return String.valueOf(System.currentTimeMillis()/1000);
	}

	public static String NewGuid() {
		return UUID.randomUUID().toString().replace("-", "");
	}

}

